"use strict";

var BookmarkStoreAdapter = function( coll, bookmarkTreeNodeId, typeToLoad ) {
  
  var that = this
    , callFilterBookmarks = function( bookmarkTreeNodeArr ) {
    that.filterBookmarks( bookmarkTreeNodeArr );
  };
  
  this.BOOKMARK_TYPE_URI    = 'url';
  this.BOOKMARK_TYPE_FOLDER = 'folder';
  
  this.type               = typeToLoad === 'folder' ? this.BOOKMARK_TYPE_FOLDER : this.BOOKMARK_TYPE_URI;
  this.collection         = coll;
  this.loadedBookmarks    = [];

  this.loadBookmarksFromFolder( bookmarkTreeNodeId.toString(), callFilterBookmarks );
  
};

_.extend( BookmarkStoreAdapter.prototype, {
  
  loadBookmarksFromFolder : function( bookmarkTreeNodeId, callback ) {
    chrome.bookmarks.getChildren( bookmarkTreeNodeId, callback );
  }
  
, filterBookmarks         : function( bookmarkTreeNodeArr ) {
    var bookmarks = []
      , that      = this;
    
    _( bookmarkTreeNodeArr ).chain()
      .filter (  function( bookmarkTreeNode )              {

        //TODO: make switch for folder / uri loading  
        return that.type === that.BOOKMARK_TYPE_URI ? bookmarkTreeNode.hasOwnProperty( 'url' ) : !bookmarkTreeNode.hasOwnProperty( 'url' );
        
        //return bookmarkTreeNode.hasOwnProperty( that.BOOKMARK_TYPE_URI );
        
      } )
      .sortBy (  function( bookmarkTreeNode )              { return bookmarkTreeNode.index; } )
      .each   (  function( bookmarkTreeNode, index, list ) { bookmarks.push( { node: bookmarkTreeNode, index: index } ); } );
    
    if( bookmarks.length ) {
      this.loadedBookmarks = bookmarks;
      this.collection.fetch( {
        success : function( collection, response ){
          console.log('loaded',response)  
        }
      , error   : function( collection, response ){
        
      }
      } );
    }
  }
  
  
  
  
  /*
   * 
   * read = find or findAll 
   * create = create, use save 
   * update = update, use save
   * delete = destroy
   * 
   */

//TODO: use chrome bookmarks api! in all of this object!
/*  
  save    : function() {
    //TODO: chrome bookmarks save
  }

, create  : function( model ) {
    if (!model.id) model.id = model.attributes.id = guid();
    this.data[ model.id ] = model;
    this.save();
    return model;
  }

, update  : function( model ) {
    this.data[ model.id ] = model;
    this.save();
    return model;
  }
*/

, find    : function( model ) {
    return this.loadedBookmarks[ model.id ];
  }

, findAll : function() {
    return _.values( this.loadedBookmarks );
  }

/*
, destroy : function( model ) {
    delete this.data[ model.id ];
    this.save();
    return model;
  }
*/

} );